package practica1.ui.dialog;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import javax.swing.*;
import practica1.Practica1;
import practica1.language.Language;
import practica1.manejoExperimento.ManejoExperimento;

/**
 * JDialog que permite abrir un Experimento
 * @author Miguel González - Ceura
 */
public class DialogAbrirExperimento extends JDialog  {
    public static final int CANCELAR = 0;
    public static final int ACEPTAR = 1;
    
    private JTextField txtRutaExperimento;
    private JButton btnExaminarExperimento;
    private JCheckBox chkAbrirBD;
    private JComboBox cboExperimentosBD;
    
    private int action = 0;
    
    public DialogAbrirExperimento(Frame parent) {
        super(parent);
        
        init();
        
        setLocationRelativeTo(parent);
    }
    
    public DialogAbrirExperimento() {
        super();
        
        init();
        
        setLocationRelativeTo(null);
    }
    
    private void init() {
        Container contentPane = getContentPane();
        setSize(600, 200);
        setTitle(Language.getI().getP("ABRIR_EXPERIMENTO"));
        setModal(true);
        contentPane.setLayout(new BorderLayout());
        
        
        JLabel lblRutaExperimento = new JLabel(
                Language.getI().getP("RUTA_EXPERIMENTO"));
        txtRutaExperimento = new JTextField(15);
        txtRutaExperimento.setText(System.getProperty("user.home"));
        txtRutaExperimento.setEditable(false);
        txtRutaExperimento.setBackground(Color.WHITE);
        btnExaminarExperimento = new JButton(
                Language.getI().getP("EXAMINAR"));
        btnExaminarExperimento.addActionListener(new PulsadoExaminar());
        
        JLabel lblExperimento = new JLabel(Language.getI().getP("EXPERIMENTO"));
        
        chkAbrirBD = new JCheckBox(Language.getI().getP("ABRIR_BD"));
        chkAbrirBD.addActionListener(new EscuchadorAbrirBD());
        
        ArrayList<String> exBD = ManejoExperimento.obtenerExperimentosBD();
        cboExperimentosBD = new JComboBox(exBD.toArray());
        cboExperimentosBD.setEnabled(false);
        
        JLabel lblAviso = new JLabel();
        lblAviso.setForeground(Color.RED);
        lblAviso.setBorder(BorderFactory.createEmptyBorder(0,0,0,50));
        //Si no hay conexión contra base de datos
        if(!ManejoExperimento.isConectado()) {
            chkAbrirBD.setEnabled(false);
            cboExperimentosBD.setEnabled(false);
            lblExperimento.setEnabled(false);
            lblAviso.setText(Language.getI().getP("NO_HAY_CONEXION"));
        }
        
        JButton btnAceptar = new JButton(Language.getI().getP("ACEPTAR"));
        btnAceptar.addActionListener(new PulsadoAceptar());
        JButton btnCancelar = new JButton(Language.getI().getP("CANCELAR"));
        btnCancelar.addActionListener(new PulsadoCancelar());
        
        JPanel panelCentro = new JPanel(new GridBagLayout());
        
        GridBagConstraints c = new GridBagConstraints();
        c.fill = GridBagConstraints.HORIZONTAL;
        c.ipadx = 25;
        
        c.gridx = 0;
        c.gridy = 0;
        c.gridwidth = 1;
        panelCentro.add(lblRutaExperimento, c);
        c.gridx = 1;
        c.gridy = 0;
        c.gridwidth = 2;
        panelCentro.add(txtRutaExperimento, c);
        c.gridx = 1;
        c.gridy = 1;
        c.gridwidth = 1;
        c.insets = new Insets(5,0,5,5); //Padding boton
        panelCentro.add(btnExaminarExperimento, c);
        c.gridx = 2;
        c.gridy = 1;
        c.insets = new Insets(0,0,0,0); //Restauramos el padding
        panelCentro.add(new JLabel(), c);
        c.gridx = 0;
        c.gridy = 2;
        c.gridwidth = 3;
        panelCentro.add(chkAbrirBD, c);
        c.gridx = 0;
        c.gridy = 3;
        c.gridwidth = 1;
        panelCentro.add(lblExperimento, c);
        c.gridx = 1;
        c.gridy = 3;
        c.gridwidth = 1;
        panelCentro.add(cboExperimentosBD, c);
        
        contentPane.add(panelCentro, BorderLayout.CENTER);
        
        //Panel inferior
        JPanel panelInferior = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        panelInferior.add(lblAviso);
        panelInferior.add(btnCancelar);
        panelInferior.add(btnAceptar);
        contentPane.add(panelInferior, BorderLayout.SOUTH);
    }
    
    /**
     * Devuelve la ruta del experiment
     * @return String rutaExperimento
     */
    public String getRutaExperimento() {
        return txtRutaExperimento.getText();
    }
    
    public boolean isAbrirBD() {
        return chkAbrirBD.isSelected();
    }
    
    /**
     * Devuelve la acción realizada
     * @return int action
     */
    public int getAction() {
        return action;
    }
    
    public String getNombreExperimentoBD() {
        return cboExperimentosBD.getSelectedItem().toString();
    }
    
    /**
     * Evento que se produce al pulsar examinar
     */
    private class PulsadoExaminar implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            JFileChooser fc = new JFileChooser();
            //Solo permitimos mostrar directorios
            fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
            fc.setDialogTitle(Language.getI().getP("RUTA_EXPERIMENTO"));
            fc.setCurrentDirectory(new File(txtRutaExperimento.getText()));
            //Mostramos la ventana y obtenemos su respuesta
            int res = fc.showOpenDialog(null);

            if(res == JFileChooser.APPROVE_OPTION) {
                //Crear un objeto File la ruta elegida
                File rutaElegida = fc.getSelectedFile();
                //Mostramos la ruta elegida
                txtRutaExperimento.setText(rutaElegida.getAbsolutePath());
            }
        }
    }
    
    private class EscuchadorAbrirBD implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            if(chkAbrirBD.isSelected()) {
                btnExaminarExperimento.setEnabled(false);
                cboExperimentosBD.setEnabled(true);
            } else {
                btnExaminarExperimento.setEnabled(true);
                cboExperimentosBD.setEnabled(false);
            }
        }
    }
    
    /**
     * Evento producido al pulsar aceptar
     */
    private class PulsadoAceptar implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            aceptarAccion();
        }
    }
    
    /**
     * Accion producida al aceptar la acción
     */
    private void aceptarAccion() {
        if(estanTextosIntroducidos()) {
                action = ACEPTAR;
                setVisible(false);
        } else {
            JOptionPane.showMessageDialog(Practica1.getInstance(),
                Language.getI().getP("FALTAN_DATOS"), 
                Language.getI().getP("ADVERTENCIA"),
                JOptionPane.WARNING_MESSAGE);
        }
    }
    
    /**
     * Evento que se produce al pulsar cancelar
     */
    private class PulsadoCancelar implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            action = CANCELAR;
            setVisible(false);
        }
    }

    private boolean estanTextosIntroducidos() {
        return (chkAbrirBD.isSelected() &&
                !cboExperimentosBD.getSelectedItem().toString().isEmpty()) ||
                !txtRutaExperimento.getText().isEmpty() && !new File(
                txtRutaExperimento.getText()).isDirectory();
    }
}
